<template>
  <div class="searchresult-container">
    <!-- 搜索区 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      @search="search"
      @cancel="$router.back()"
      placeholder="请输入商品名称"
    />
    <!-- 下拉菜单 -->
    <van-dropdown-menu v-if="goods.length > 0">
      <van-dropdown-item @change="changeSort" v-model="sort" :options="option" />
    </van-dropdown-menu>
    <!-- 商品列表 -->
    <div class="goodslist">
      <div class="item" v-for="item in goods" :key="item.id">
        <img :src="item.img_url" alt />
        <div class="text">
          <div class="title ellipsis">{{ item.title }}</div>
          <div class="price">
            <span class="shopPrice">¥ {{ item.sell_price }}</span>
            <span class="marketPrice">¥ {{ item.market_price }}</span>
          </div>
          <div class="hot">
            <span>热卖中</span>
            <span>剩余{{ item.stock_quantity }}件</span>
          </div>
        </div>
      </div>
    </div>

    <van-empty v-if="goods.length === 0">暂无数据</van-empty>
  </div>
</template>

<script>
import { reqSearchGoods } from '@/api'
export default {
  data() {
    return {
      value: this.$route.query.value,
      sort: 'buy',
      option: [
        { text: '销量', value: 'buy' },
        { text: '好评数量', value: 'likes' },
        { text: '价格', value: 'sell_price' },
      ],
      goods: [],
    }
  },
  methods: {
    search() {
      this.goods = []
      // 发请求获取数据
      this.getSearchGoods()
    },
    // 切换搜索条件
    changeSort() {
      // 发请求获取数据
      this.getSearchGoods()
    },
    // 获取关键字对应的商品
    async getSearchGoods() {
      // 调用api接口
      let goods = await reqSearchGoods({ value: this.value, sort: this.sort })
      this.goods = goods
    },
  },
  mounted() {
    this.getSearchGoods()
  },
}
</script>

<style lang="scss" scoped>
.searchresult-container {
  .goodslist {
    display: flex;
    flex-wrap: wrap;

    .item {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 46%;
      padding: 2px;
      margin: 4px;
      overflow: hidden;
      background: #fff;
      border-radius: 6px;

      img {
        width: 100%;
      }

      .text {
        padding: 6px;

        .title {
          padding: 2px;
          font-size: 12px;
          color: #333;
        }

        .price {
          margin: 4px 0;

          .shopPrice {
            margin-right: 20px;
            font-size: 16px;
            color: #f00;
          }

          .marketPrice {
            font-size: 12px;
            color: #333;
            text-decoration: line-through;
          }
        }

        .hot {
          display: flex;
          justify-content: space-between;
          font-size: 14px;
          color: #645a5a;
        }
      }
    }
  }

  .van-empty {
    font-size: 14px;
    color: #969799;
  }
}
</style>
